﻿using System;
using System.Collections.Generic;
using System.Data;
using MedicService.Domain.Directory;
using MedicService.Domain.Directory.Simple;
using MedicService.Server.Factory.Directory.Simple;
using MedicService.Server.Factory.Generic;

namespace MedicService.Server.Factory.Directory {
    public class LocalityFactory : DirectoryFactory<Locality> {
        public LocalityFactory() : base("Locality") { }
        protected override void FillEntity(Locality entity, DataRow myDataRow) {
            entity.Id = (int) myDataRow["id"];
            entity.Title = (string) myDataRow["title"];

            entity.Region = new RegionFactory().Load(myDataRow["regionId"]);
        }

        public List<Locality> GetList(Region region) {
            var entities = new List<Locality>();
            var dataTable = DatabaseConnector.GetData(TableName, OrderBy, "regionId=" + region.Id);
            foreach (DataRow myDataRow in dataTable.Rows) {
                var entity = CreateEntity();
                FillEntity(entity, myDataRow);
                entities.Add(entity);
            }
            return entities;
        }

        protected override Locality CreateEntity() {
            return new Locality();
        }

        protected override string GetInsertQuery(Locality entity) {
            string q = "INSERT INTO [Locality]" 
                     + "           ([title]" 
                     + "           ,[regionId])"
                     + "     VALUES" 
                     + "           (" + Nullable(entity.Title) 
                     + "           ," + Nullable(entity.Region) + ");" 
                     + "            ";
            return q;
        }

        protected override string GetUpdateQuery(Locality entity) {
            string q = "UPDATE [Locality]" 
                     + "   SET [title] = " + Nullable(entity.Title)
                     + "      ,[regionId] = " + Nullable(entity.Region) 
                     + " WHERE id=" + entity.Id;
            return q;
        }
    }
}